<template>
  <div class="table">
    <!-- 弹窗区 -->
    <!-- 查看详情 -->
    <el-dialog
      title="工单详情"
      :visible="outerVisible"
      @close="closeOuterDialog"
      width="35%"
      custom-class="classRadius"
    >
      <div v-if="this.clickValue.taskStatusTypeEntity.statusName === '取消'">
        <el-alert title="取消" :closable="false" type="info" show-icon></el-alert>
        <div class="pic"><img src="~@/assets/images/cancle.png" /></div>
      </div>
      <div v-else-if="this.clickValue.taskStatusTypeEntity.statusName === '完成'">
        <el-alert title="完成" :closable="false" type="success" show-icon></el-alert>
        <div class="pic"><img src="~@/assets/images/complete.png" /></div>
      </div>
      <div v-else>
        <el-alert title="代办" :closable="false" type="warning" show-icon></el-alert>
        <div class="pic"><img src="~@/assets/images/await.png" /></div>
      </div>
      <div class="content">
        <div class="text">
          <p>设备编号:</p>
          <span>{{ clickValue.taskCode || '' }}</span>
        </div>
        <div class="text">
          <p>创建日期:</p>
          <span>{{ clickValue.createTime || '' }}</span>
        </div>
        <div class="text" v-if="this.clickValue.taskStatusTypeEntity.statusName === '取消'">
          <p>取消日期:</p>
          <span>{{ clickValue.updateTime || '' }}</span>
        </div>
        <div class="text" v-else-if="this.clickValue.taskStatusTypeEntity.statusName === '完成'">
          <p>完成日期:</p>
          <span>{{ clickValue.updateTime || '' }}</span>
        </div>
        <div class="text" v-else style="display: none">
          <p>取消日期:</p>
          <span>{{ clickValue.updateTime || '' }}</span>
        </div>
        <div class="text">
          <p>运营人员:</p>
          <span>{{ clickValue.userName || '' }}</span>
        </div>
        <div class="text">
          <p>工单类型:</p>
          <span>{{ clickValue.taskType.typeName || '' }}</span>
        </div>
        <div class="text">
          <p>补货数量:</p>
          <span class="count" @click="fillGoods(clickValue)">补货详情</span>
        </div>
        <div class="text">
          <p>工单方式:</p>
          <span>{{ clickValue.createType === 1 ? '手动' : '自动' }}</span>
        </div>
        <div class="text" v-if="this.clickValue.taskStatusTypeEntity.statusName === '取消'">
          <p>取消原因:</p>
          <span>{{ clickValue.desc || '' }}</span>
        </div>
        <div class="text" v-else>
          <p class="position">备注:</p>
          <span>{{ clickValue.desc || '' }}</span>
        </div>
      </div>
      <el-dialog
        width="30%"
        title="工单详情"
        :visible="innerVisible"
        @close="innerVisible = false"
        append-to-body
        custom-class="classRadius"
      >
        <el-table ref="applyTable" :data="taskDetailsList" center style="width: 100%" height="400">
          <el-table-column
            align="center"
            label="货道编号"
            property="channelCode"
            height="45"
          ></el-table-column>
          <el-table-column
            align="center"
            label="商品名称"
            property="skuName"
            height="45"
          ></el-table-column>
          <el-table-column
            align="center"
            label="当前数量"
            property="expectCapacity"
            height="45"
          ></el-table-column>
        </el-table>
      </el-dialog>
      <div solt="footer" class="dialog-footer">
        <div v-if="this.clickValue.taskStatusTypeEntity.statusName === '取消'">
          <el-button type="warning" size="small" @click="resetCreate">重新创建</el-button>
        </div>
        <div v-else-if="this.clickValue.taskStatusTypeEntity.statusName === '完成'"></div>
        <div v-else>
          <el-button type="warning" size="small" @click="concleTask">取消工单</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 新建的弹窗 -->
    <el-dialog
      :title="createTitle"
      :visible="createVisible"
      @close="closecreateDialog"
      width="35%"
      custom-class="classRadius"
    >
      <el-form
        :model="ruleFormCreate"
        :rules="rulesCreate"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="设备编号:" prop="innerCode" placeholder="请输入">
          <el-input
            v-model="ruleFormCreate.innerCode"
            @blur="innerCodeInput"
            maxlength="15"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="工单类型:" prop="productType">
          <el-select v-model="ruleFormCreate.productType" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in allTaskTypeList"
              :key="item.typeName"
              :label="item.typeName"
              :value="item.typeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="补货数量:" prop="delivery">
          <template>
            <div class="fillList">
              <i class="iconfont icon-dingdan"></i><span @click="openApplyDialog">补货清单</span>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="运营人员:" prop="assignorId">
          <el-select v-model="ruleFormCreate.assignorId" placeholder="请选择" style="width: 100%">
            <el-option
              v-show="roleNameList.lengtn !== 0"
              v-for="item in roleNameList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" prop="desc">
          <el-input
            type="textarea"
            v-model="ruleFormCreate.desc"
            maxlength="40"
            placeholder="请输入内容(不超过40个字符)"
            show-word-limit
            :autosize="{ minRows: 4, maxRows: 6 }"
          ></el-input>
        </el-form-item>
        <el-form-item center>
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="createVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 补货清单 数据列表 -->
    <el-dialog
      title="补货详情"
      :visible="applyVisible"
      @close="closeApplyDialog"
      width="35%"
      custom-class="classRadius"
    >
      <el-table ref="applyTable" :data="applyList" center style="width: 100%" height="400">
        <el-table-column
          align="center"
          label="货道编号"
          property="channelCode"
          width="80"
          height="45"
        ></el-table-column>
        <el-table-column
          align="center"
          label="商品名称"
          property="sku.brandName"
          width="120"
          height="45"
        ></el-table-column>
        <el-table-column
          align="center"
          label="当前数量"
          property="currentCapacity"
          width="100"
          height="45"
        ></el-table-column>
        <el-table-column
          align="center"
          label="还可添加"
          property="inputMaxNum"
          width="100"
          height="45"
        ></el-table-column>
        <el-table-column align="center" label="补满数量" width="220" height="45">
          <template slot-scope="{ row }">
            <div v-if="row.inputMaxNum !== '-'">
              <el-input-number
                v-model="row.needNum"
                controls-position="right"
                :min="0"
                :max="row.inputMaxNum === '-' ? 0 : row.inputMaxNum"
              ></el-input-number>
            </div>
            <el-row v-else>货道暂无商品</el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-row slot="footer" type="flex" justify="center" class="dialog-footer">
        <el-button @click="applyDetails">取 消</el-button>
        <el-button type="primary" @click="applyVisible = false">确认</el-button>
      </el-row>
    </el-dialog>
    <!-- 工单配置 -->
    <el-dialog
      title="工单配置"
      :visible="pluginsVisible"
      @close="closePluginsDialog"
      width="35%"
      custom-class="classRadius"
    >
      <el-form :model="pluginsNumModel" :rules="pluginsNumRules"
        ><el-form-item label="补货警戒线:" label-width="100px" prop="pluginsNum">
          <template>
            <el-input-number
              class="inputNum"
              size="larger"
              v-model="pluginsNumModel.pluginsNum"
              controls-position="right"
              width="500px"
            ></el-input-number> </template></el-form-item
      ></el-form>
      <el-row slot="footer" type="flex" justify="center" class="dialog-footer">
        <el-button @click="pluginsVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmPlugins">确认</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  operatorListAPI,
  channelListAPI,
  taskDetailsAPI,
  creatTaskAPI,
  taskInfoAPI,
  supplyAlertValueAPI,
  autoSupplyConfigAPI,
  concleTaskAPI,
  allTaskTypeAPI
} from '@/api'
export default {
  name: 'Table',
  props: {
    searchTaskArray: {
      type: Array
    }
  },
  data() {
    // 自定义校验规则
    const validatePass = (rules, value, callback) => {
      setTimeout(() => {
        if (!this.roleNameList.length) return callback(new Error('工单号不存在'))
      }, 1500)
    }
    return {
      // 防抖
      timer: null,
      //  详情弹窗
      outerVisible: false,
      innerVisible: false,
      // 新建弹窗
      createVisible: false,
      // 补货清单弹窗
      applyVisible: false,
      // 工单配置弹窗
      pluginsVisible: false,
      // 工单配置的数据
      pluginsNumModel: {
        pluginsNum: 0
      },
      pluginsNumRules: {
        pluginsNum: [{ required: true, message: '请输入警戒值', trigger: 'blur' }]
      },
      // 工单点击项的数据
      clickValue: {
        taskType: {
          typeName: '' // 必须定义数据
        },
        taskStatusTypeEntity: {
          statusName: '' // 代办取消完成
        }
      },
      // 新建工单的配置信息
      ruleFormCreate: {
        assignorId: '',
        innerCode: '',
        productType: '',
        userId: 1,
        desc: '',
        createType: 1,
        details: []
      },
      // 规则校验
      rulesCreate: {
        innerCode: [
          { required: true, message: '请输入设备编号', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: ['blur', 'input'] }
        ],
        productType: [{ required: true, message: '请选择工单类型', trigger: 'blur' }],
        assignorId: [{ required: true, message: '请选择运营人员', trigger: 'blur' }],
        desc: [
          { required: true, message: '请输入备注(不超过40字)', trigger: 'blur' },
          { min: 1, max: 40, message: '长度在 1 到 40 个字符', trigger: 'blur' }
        ]
      },
      // 新建输入框的运营员列表
      roleNameList: [],
      // 补货清单列表
      applyList: [],
      // 外层弹窗的捕获详情列表
      taskDetailsList: [],
      // 获取所有工单类型
      allTaskTypeList: [],
      // 控制标题的占位
      createTime: ''
    }
  },
  created() {
    // 获取所有工单类型
    this.allTaskType()
  },
  mounted() {
    this.$bus.$on('createVisibleFn', () => {
      this.createVisible = true
    })
    this.$bus.$on('taskPlugins', () => {
      this.taskPlugins()
    })
    this.$bus.$on('openOuterDialog', (row) => {
      this.openOuterDialog(row)
    })
  },
  beforeDestroy() {
    this.$bus.$off() // 销毁所有全局事件
  },
  // 计算标题未完成
  computed: {
    createTitle() {
      return this.createTime ? '重建工单' : '新增工单'
    }
  },
  methods: {
    // 所有工单类型
    async allTaskType() {
      try {
        const res = await allTaskTypeAPI()
        res.data = res.data.filter((item) => item.typeName === '补货工单')
        this.allTaskTypeList = res.data
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 列表操作的查看详情 // 外层弹窗
    openOuterDialog(value) {
      // console.log(value)
      this.clickValue = value
      this.outerVisible = true
    },
    // 外层弹窗的补货详情
    async fillGoods(value) {
      this.innerVisible = true
      const res = await taskDetailsAPI(value.taskId)
      this.taskDetailsList = res.data
    },
    // 外层弹窗关闭事件
    closeOuterDialog() {
      this.outerVisible = false
    },
    closecreateDialog() {
      // 新增工单的配置信息重置
      this.ruleFormCreate = {
        assignorId: '',
        innerCode: '',
        productType: '',
        userId: 1,
        desc: '',
        createType: 1,
        details: []
      }
      this.createTime = ''
      this.createVisible = false
    },
    // 新增工单的确认
    async submitForm() {
      if (
        !this.ruleFormCreate.assignorId ||
        !this.ruleFormCreate.innerCode ||
        !this.ruleFormCreate.productType ||
        !this.ruleFormCreate.desc
      ) {
        return this.$message({
          type: 'warning',
          message: '请输入内容',
          offset: 75
        })
      }
      try {
        const res = await creatTaskAPI(this.ruleFormCreate)
        this.$message({
          type: 'success',
          message: '新增成功',
          offset: 75
        })
        this.$emit('freshPage')
        this.createVisible = false
        return Promise.resolve(res)
      } catch (error) {
        this.$message({
          type: 'error',
          message: `${error.response.data}`,
          offset: 75
        })
        // return Promise.reject(error.response.data)
      }
    },
    // 获取运营人员列表
    innerCodeInput() {
      this.timer = setTimeout(async () => {
        clearTimeout(this.timer)
        const res = await operatorListAPI(this.ruleFormCreate.innerCode)
        this.roleNameList = res.data
      }, 1000)
    },
    // 补货清单关闭与打开
    async openApplyDialog() {
      if (!this.roleNameList.length) {
        return this.$message({
          type: 'warning',
          message: '请输入正确工单',
          offset: 75
        })
      }
      const res = await channelListAPI(this.ruleFormCreate.innerCode)
      res.data.forEach((item) => {
        if (item.sku) {
          const needNum =
            item.maxCapacity > item.currentCapacity ? item.maxCapacity - item.currentCapacity : 0
          item.inputMaxNum = needNum
          if (needNum > 0) {
            this.ruleFormCreate.details.push({
              channelCode: item.channelCode,
              expectCapacity: needNum,
              skuId: item.skuId,
              skuImage: item.sku.skuImage,
              skuName: item.sku.skuName
            })
          }
          this.$set(item, 'needNum', needNum)
        } else {
          this.$set(item, 'sku', { brandName: '-' })
          item.currentCapacity = '-'
          item.inputMaxNum = '-'
          item.needNum = 0
        }
      })
      this.applyList = res.data
      this.applyVisible = true
    },
    // 关闭补货清单
    closeApplyDialog() {
      this.applyVisible = false
    },
    // 重新创建
    async resetCreate() {
      const res = await taskInfoAPI(this.clickValue.taskId)
      console.log(res.data)
      this.ruleFormCreate.innerCode = res.data.innerCode
      this.ruleFormCreate.productType = res.data.productTypeId
      this.ruleFormCreate.desc = res.data.desc
      this.createTime = res.data.createTime
      // this.ruleFormCreate.assignorId = res.data.assignorId
      this.createVisible = true
      // console.log(this.ruleFormCreate)
      // 获取运维人员数据
      this.innerCodeInput()
    },
    // 工单配置
    async taskPlugins() {
      this.pluginsVisible = true
      const res = await supplyAlertValueAPI()
      this.pluginsNumModel.pluginsNum = res.data
    },
    // 工单配置的关闭事件
    closePluginsDialog() {
      this.pluginsVisible = false
    },
    // 配置确认事件
    async confirmPlugins() {
      this.pluginsVisible = false
      try {
        const res = await autoSupplyConfigAPI(this.pluginsNumModel.pluginsNum)
        this.$message({
          type: 'success',
          message: '修改成功',
          offset: 75
        })
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 取消工单
    concleTask() {
      this.$confirm('取消工单后，将不能恢复，是否确认取消？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await concleTaskAPI({
          taskId: this.clickValue.taskId,
          desc: this.clickValue.decs
        })
        this.$message({
          type: 'success',
          message: '取消成功!',
          offset: 75
        })
        this.$emit('freshPage') // 刷新页面
        this.outerVisible = false
      })
    },
    // 补货清单的补货详情取消
    applyDetails() {
      this.ruleFormCreate.details = []
      this.applyVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  .fillList {
    color: #5f84ff;
    cursor: pointer;
  }
}
.el-dialog {
  position: relative;
  background-color: #fff;
  .pic {
    position: absolute;
    top: 70px;
    right: 80px;
    width: 80px;
    height: 120px;
  }
  .content {
    width: 100%;
    min-height: 200px;
    display: flex;
    flex-wrap: wrap;
    margin-top: 20px;
    .text {
      width: 260px;
      height: 36px;
      display: flex;
      font-size: 14px;
      color: #666;
      text-align: center;
      // line-height: 36px;
       .position{
        width: 40px;
      }
      p {
        margin-left: 40px;
      }
      span {
        margin-left: 20px;
        // line-height: 15px;
      }
      .count {
        color: #5f84ff;
        cursor: pointer;
      }
    }
  }
  .dialog-footer {
    text-align: center;
  }
}
.el-alert {
  height: 60px;
  /deep/.el-icon-info:before {
    font-size: 30px;
    color: #333;
  }
  /deep/.el-icon-success:before {
    font-size: 30px;
    // color: #333;
  }
  /deep/.el-icon-warning:before {
    font-size: 30px;
    // color: #333;
  }
  /deep/.el-alert__title {
    margin-left: 10px;
    color: #333;
  }
}
/deep/.el-table th.el-table__cell {
  background-color: rgb(243, 246, 251);
}
/deep/tr.el-table__row {
  height: 45px !important;
}

/deep/.el-table td.el-table__cell {
  border: none;
  height: 0px;
  padding: 0;
  .el-button {
    height: 30px;
    line-height: 1px;
    margin: 10px 0 10px 10px;
    width: 80px;
    color: #5f84ff;
  }
}
/deep/.el-table th.el-table__cell.is-leaf {
  border: none;
}
/deep/.el-button--warning {
  background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
  text-align: center;
  .icon-jiahao:before {
    content: '\e726';
    margin-right: 5px;
  }
}
/deep/.el-button--info {
  background-color: #fbf4f0 !important;
  border: none;
  color: #333;
}
/deep/.el-table::before {
  height: 0;
}
.inputNum {
  width: 100%;
}
</style>
<style lang="less">
.classRadius {
  border-radius: 10px;
}
</style>
